import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Checkbox, Button, Balloon } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { Header, Content, Section, ButtonIcon, YunxiaoTable, YunxiaoIcon } from '@alife/devops-ui';
import { navigate, navigateOpen } from 'utils/router';
import track, { enterPage, Perf } from 'utils/track';
import { getFeature } from 'utils/features';
import FilterForm from './filterForm';
import Qs from 'qs';
import * as actions from '../actions/index';
import dayjs from 'dayjs';
import Moment from 'moment';
import BillingStatus from 'components/billing';
import BillingMessage from 'components/billing/message';
import intl from '../../../../../../../../../locale';

const BEHAVIORS = {
  FREQUENT_PULL: intl.get({
    id: 'code-assets.securityNotify.containers.root.LargePullCodeBase',
    defaultMessage: '大量拉取代码库',
  }),
  SENSITIVE_DEL_REPO: intl.get({
    id: 'code-assets.securityNotify.containers.root.AbnormalDatabaseDeletion',
    defaultMessage: '异常删库',
  }),
  SENSITIVE_MOD_MEMBER: intl.get({
    id: 'code-assets.securityNotify.containers.root.ModifyDatabaseMembers',
    defaultMessage: '修改库成员',
  }),
  SENSITIVE_ORG_ADD_ADMIN: intl.get({
    id: 'code-assets.securityNotify.containers.root.AddAnEnterpriseAdministrator',
    defaultMessage: '添加企业管理员',
  }),
  SENSITIVE_ORG_ADD_OWNER: intl.get({
    id: 'code-assets.securityNotify.containers.root.AddAnEnterpriseOwner',
    defaultMessage: '添加企业拥有者',
  }),
  SENSITIVE_ORG_DEL_ADMIN: intl.get({
    id: 'code-assets.securityNotify.containers.root.DeleteAnEnterpriseAdministrator',
    defaultMessage: '删除企业管理员',
  }),
  SENSITIVE_ORG_DEL_OWNER: intl.get({
    id: 'code-assets.securityNotify.containers.root.DeleteAnEnterpriseOwner',
    defaultMessage: '删除企业拥有者',
  }),
  REPO_OPERATION: intl.get({
    id: 'code-assets.securityNotify.containers.root.DatabaseOperations',
    defaultMessage: '库操作',
  }),
  AUTHORITY_CHANGE: intl.get({
    id: 'code-assets.securityNotify.containers.root.PermissionChange',
    defaultMessage: '权限变更',
  }),
};

class Root extends Component {
  static propTypes = {
    SecuritySettingData: PropTypes.arrayOf(PropTypes.object),
    isLoadingTable: PropTypes.bool,
    pageSize: PropTypes.number,
    currentPage: PropTypes.number,
    SecurityRecordData: PropTypes.arrayOf(PropTypes.object),
    getSecuritySettingData: PropTypes.func,
    isSensitiveBehaviorEnable: PropTypes.bool,
    getParamsData: PropTypes.func,
    getOrgSettingData: PropTypes.func,
    updateSecuritySetting: PropTypes.func,
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.securityNotify.containers.root.SecurityNotificationCloudEffectCodeup',
      defaultMessage: '安全通知 · 云效 Codeup',
    });

    const { currentPage, pageSize } = this.props;
    this.props.getSecuritySettingData();
    this.props.getParamsData(currentPage, pageSize);
    this.props.getOrgSettingData();

    enterPage('Organization-Settings-Security Notify', {
      sendPerf: false,
    });
  }

  // 安全通知checkbox变化时触发
  onCheckChange = (checked, index, record, value) => {
    const recordArr = record.notify_method ? record.notify_method.split(',') : [];
    checked ? recordArr.push(value) : recordArr.splice(recordArr.indexOf(value), 1);
    record.notify_method = recordArr.join(',');

    // 埋点
    if (record.name === 'SENSITIVE_OP' && record.notify_method !== '') {
      if (record.notify_method.indexOf('INSITE') >= 0) {
        track({
          action: 'check_internal_message',
          page: 'Organization-Settings-Security Notify',
          type: 'sensitive_behavior_monitoring',
        });
      }
      if (record.notify_method.indexOf('EMAIL') >= 0) {
        track({
          action: 'check_email',
          page: 'Organization-Settings-Security Notify',
          type: 'sensitive_behavior_monitoring',
        });
      }
      if (record.notify_method.indexOf('DINGDING') >= 0) {
        track({
          action: 'check_ding',
          page: 'Organization-Settings-Security Notify',
          type: 'sensitive_behavior_monitoring',
        });
      }
    }

    this.props.updateSecuritySetting(record);
  };

  onPageNoChange = (page) => {
    this.props.getParamsData(page, this.props.pageSize, this.props.paramsData);
  };

  onPageSizeChange = (pageSize) => {
    this.props.updateData({
      pageSize,
    });
    this.props.getParamsData(1, pageSize, this.props.paramsData);
  };

  onDownloadClick = () => {
    const { paramsData } = this.props;
    const searchData = Qs.stringify(paramsData);
    navigateOpen(
      `/api/v4/organization/${window.FORCE.organization.id}/security_notify/download?${searchData}`,
    );
  };

  navToBehaviorPage = () => {
    track({
      action: 'to_see_sensitive_behavior_monitoring',
      page: 'Organization-Settings-Security Notify',
      type: '',
    });

    navigate('/settings/member_behavior_security');
  };

  // 渲染安全通知表单的类别
  renderName = (value) => {
    const { isSensitiveBehaviorEnable } = this.props;
    if (value === 'DEL_REPO') {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.CodeLibraryDeletionNotification',
        defaultMessage: '代码库删除通知',
      });
    } else if (value === 'TRANSFER_REPO') {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.CodeLibraryTransferNotification',
        defaultMessage: '代码库转移通知',
      });
    } else if (value === 'SENSITIVE_OP') {
      return (
        <span style={{ display: 'flex', alignItems: 'center' }}>
          {intl.get({
            id: 'code-assets.securityNotify.containers.root.SensitiveBehaviorAlerts',
            defaultMessage: '敏感行为告警',
          })}

          {isSensitiveBehaviorEnable ? null : (
            <Balloon
              align="t"
              trigger={<ButtonIcon text name="question-line" />}
              closable={false}
            >
              {
                <span>
                  {intl.get({
                    id: 'code-assets.securityNotify.containers.root.EnableSensitiveBehaviorMonitoringTo',
                    defaultMessage: '开启敏感行为监测，帮助企业快速识别敏感行为',
                  })}

                  <Button
                    type="primary"
                    onClick={this.navToBehaviorPage}
                    style={{ position: 'absolute', right: 20, bottom: 6 }}
                    text
                  >
                    {intl.get({
                      id: 'code-assets.securityNotify.containers.root.Enable',
                      defaultMessage: '前往开启',
                    })}
                  </Button>
                </span>
              }
            </Balloon>
          )}
        </span>
      );
    } else if (value === 'ORG_PUBLIC_REPO') {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.CodeLibraryPublicNotification',
        defaultMessage: '代码库公开通知',
      });
    } else if (value === 'DEL_GROUP') {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.CodeGroupDeletionNotification',
        defaultMessage: '代码组删除通知',
      });
    } else if (value === 'ORG_PUBLIC_GROUP') {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.CodeGroupPublicNotification',
        defaultMessage: '代码组公开通知',
      });
    } else {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.UnknownType',
        defaultMessage: '未知类型',
      });
    }
  };

  // 渲染安全通知表单的通知项
  renderCheck = (value, index, record, type) => {
    const { isSensitiveBehaviorEnable } = this.props;
    return (
      <Checkbox
        defaultChecked={value.indexOf(type) > -1}
        disabled={record.name === 'SENSITIVE_OP' ? !isSensitiveBehaviorEnable : false}
        onChange={(checked) => this.onCheckChange(checked, index, record, type)}
      />
    );
  };

  // 渲染安全通知记录表单的时间
  renderTime = (value) => {
    return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
  };

  // 渲染安全通知记录表单的通知描述
  renderDesc = (value, index, record) => {
    const { action_type, operator, project, ip, detail } = record;
    const user = operator ? operator.name || operator.username : '----';
    const ipAddress = ip && ip.ip_address ? ip.ip_address : '----';

    let action;
    if (action_type === 'TRANSFER_REPO') {
      action = intl.get({
        id: 'code-assets.securityNotify.containers.root.TransferredTheCodeLibrary',
        defaultMessage: '转移了代码库',
      });
    } else if (action_type === 'DEL_REPO') {
      action = intl.get({
        id: 'code-assets.securityNotify.containers.root.DeletedTheCodeLibrary',
        defaultMessage: '删除了代码库',
      });
    } else if (action_type === 'ORG_PUBLIC_REPO') {
      action = intl.get({
        id: 'code-assets.securityNotify.containers.root.ExposedCodeLibrary',
        defaultMessage: '公开了代码库',
      });
    } else if (action_type === 'DEL_GROUP') {
      action = intl.get({
        id: 'code-assets.securityNotify.containers.root.DeletedCodeGroup',
        defaultMessage: '删除了代码组',
      });
    } else if (action_type === 'ORG_PUBLIC_GROUP') {
      action = intl.get({
        id: 'code-assets.securityNotify.containers.root.ExposedCodeGroups',
        defaultMessage: '公开了代码组',
      });
    } else if (action_type === 'SENSITIVE_OP') {
      const actionArr = detail ? detail.split(',') : [];
      let str = '';
      for (const operationType in actionArr) {
        str += intl.get(
          {
            id: 'code-assets.securityNotify.containers.root.Behaviorsactionarroperationtype',
            defaultMessage: '{BEHAVIORSActionArrOperationType}、',
          },
          { BEHAVIORSActionArrOperationType: BEHAVIORS[actionArr[operationType]] },
        );
      }
      str = str.endsWith('、') ? str.substring(0, str.length - 1) : str;
      action = str;
    } else {
      return intl.get({
        id: 'code-assets.securityNotify.containers.root.UnknownOperation',
        defaultMessage: '未知操作',
      });
    }

    return (
      <span>
        {ip && ip.ip_location ? (
          <span>
            {action_type === 'SENSITIVE_OP' ? (
              <span>
                [{user}]{action} IP: {ipAddress}
                {intl.get({
                  id: 'code-assets.securityNotify.containers.root.Location',
                  defaultMessage: '地点：',
                })}
                {ip.ip_location}
              </span>
            ) : (
              <span>
                [{user}]{action}[{project.path_with_namespace}
                {intl.get({
                  id: 'code-assets.securityNotify.containers.root.Ip',
                  defaultMessage: '] IP：',
                })}
                {ipAddress}
                {intl.get({
                  id: 'code-assets.securityNotify.containers.root.Location',
                  defaultMessage: '地点：',
                })}
                {ip.ip_location}
              </span>
            )}
          </span>
        ) : (
          <span>
            {action_type === 'SENSITIVE_OP' ? (
              <span>
                [{user}]{action} IP: {ipAddress}
              </span>
            ) : (
              <span>
                [{user}]{action}[{project.path_with_namespace}
                {intl.get({
                  id: 'code-assets.securityNotify.containers.root.Ip',
                  defaultMessage: '] IP：',
                })}
                {ipAddress}
              </span>
            )}
          </span>
        )}
      </span>
    );
  };

  BillingHanderRender = () => {
    const { enterprisePackage } = this.props;
    const billingStatus = enterprisePackage && enterprisePackage.status;
    const billingPlanType = enterprisePackage && enterprisePackage.plan_type;
    const billingTryOrder =
      (enterprisePackage && enterprisePackage.is_can_use_trial_feature) ||
      (enterprisePackage && enterprisePackage.is_has_used_trial_feature);
    const billingnewS =
      billingPlanType === 'premiumVersion' &&
      (billingStatus === 'limit' || billingStatus === 'strictLimit');

    if (billingnewS) {
      return (
        <BillingStatus
          visi
          status={billingStatus}
          biObj={enterprisePackage}
          isClose={!billingnewS}
          billingOpenHander={this.props.getOrgplan}
        />
      );
    } else if (billingPlanType !== 'premiumVersion' && billingTryOrder) {
      return (
        <BillingStatus
          visi
          status={billingStatus}
          biObj={enterprisePackage}
          isClose={!billingnewS}
          billingOpenHander={this.props.getOrgplan}
        />
      );
    }
  };

  render() {
    const { SecuritySettingData, SecurityRecordData, isLoadingTable, currentPage, total } =
      this.props;
    // 隐藏库转移
    const curSecuritySettingData = SecuritySettingData
      ? SecuritySettingData.filter((item) => {
          if (getFeature('organization.setting.member_behavior_security.not_need')[item.name]) {
            return false;
          }
          return item.name !== 'TRANSFER_REPO';
        })
      : [];
    const { enterprisePackage } = this.props;
    const billing =
      enterprisePackage && enterprisePackage.order_info && enterprisePackage.order_info.order_id;
    const billingValue = billing
      ? Moment(enterprisePackage.order_info.end_date).diff(Moment(), 'day')
      : 0;
    const biValueStatus = billingValue < 0;
    // const billingStatus = enterprisePackage && enterprisePackage.status;
    // const billingTryOrder = enterprisePackage && enterprisePackage.is_can_use_trial_feature;
    return (
      <>
        {billing && !biValueStatus && <BillingMessage moment={billingValue} />}
        {this.BillingHanderRender()}
        {/* {
        (billingTryOrder || (billingStatus && billingStatus !== 'normal'))
          && <BillingStatus visi status={billingStatus} biObj={enterprisePackage} />
        } */}
        <Header
          title={intl.get({
            id: 'code-assets.securityNotify.containers.root.SecurityNotification',
            defaultMessage: '安全通知',
          })}
          className={`${billing && !biValueStatus ? 'after-billingMessage' : ''}`}
        />
        <Content>
          {!isLoadingTable ? <Perf page="Organization-Settings-Security Notify" /> : null}
          <Section
            title={'安全通知设置'}
            subTitle={intl.get({
              id: 'code-assets.securityNotify.containers.root.NotificationScopeEnterpriseAdministratorIncluding',
              defaultMessage: '通知范围：企业管理员（包括拥有者、管理员）',
            })}
          >
            <YunxiaoTable
              hasBorder
              dataSource={curSecuritySettingData}
              className="security-notify-table"
            >
              <YunxiaoTable.Column
                title={intl.get({
                  id: 'code-assets.securityNotify.containers.root.Category',
                  defaultMessage: '类别',
                })}
                dataIndex="name"
                cell={this.renderName}
              />

              {getFeature('organization.setting.security_notification.insite_notification') && <YunxiaoTable.Column
                title={intl.get({
                  id: 'code-assets.securityNotify.containers.root.InSiteNotification',
                  defaultMessage: '站内通知',
                })}
                dataIndex="notify_method"
                cell={(value, index, record) => this.renderCheck(value, index, record, 'IN_SITE')}
              />}

              <YunxiaoTable.Column
                title={intl.get({
                  id: 'code-assets.securityNotify.containers.root.EmailNotification',
                  defaultMessage: '邮箱通知',
                })}
                dataIndex="notify_method"
                cell={(value, index, record) => this.renderCheck(value, index, record, 'EMAIL')}
              />
            </YunxiaoTable>
          </Section>
          <Section
            style={{ position: 'relative' }}
            title={intl.get({
              id: 'code-assets.securityNotify.containers.root.SecurityNotificationRecords',
              defaultMessage: '安全通知记录',
            })}
            operation={
              <>
                <FilterForm {...this.props} />
                <Balloon.Tooltip
                  trigger={
                    <Button
                      type="primary"
                      text
                      onClick={this.onDownloadClick}
                      style={{ marginLeft: 8 }}
                    >
                      <YunxiaoIcon type="export-module-line" />
                      {intl.get({
                        id: 'code-assets.securityNotify.containers.root.Export',
                        defaultMessage: '导出',
                      })}
                    </Button>
                  }
                  align="tr"
                >
                  {intl.get({
                    id: 'code-assets.securityNotify.containers.root.AMaximumExportBarIf',
                    defaultMessage: '一次最多导出 10000 条，若超过，可通过筛选分次导出',
                  })}
                </Balloon.Tooltip>
              </>
            }
          >
            <YunxiaoTable
              className="security-notify-desc"
              hasBorder={false}
              dataSource={SecurityRecordData}
              loading={isLoadingTable}
            >
              <YunxiaoTable.Column
                title={intl.get({
                  id: 'code-assets.securityNotify.containers.root.Date',
                  defaultMessage: '日期',
                })}
                dataIndex="gmt_create"
                width={1}
                cell={this.renderTime}
              />

              <YunxiaoTable.Column
                title={intl.get({
                  id: 'code-assets.securityNotify.containers.root.NotificationDescription',
                  defaultMessage: '通知描述',
                })}
                width={2}
                cell={this.renderDesc}
              />
            </YunxiaoTable>
            <Pagination
              onChange={this.onPageNoChange}
              current={currentPage}
              total={total}
              pageSize={this.props.pageSize}
              onPageSizeChange={this.onPageSizeChange}
              noBorderTop
            />
          </Section>
        </Content>
      </>
    );
  }
}

export default connect(
  (state) => ({
    ...state.organization.settings.securityNotify,
    enterprisePackage: state.organization.settings.settings.enterprisePackage,
  }),
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
